package com.smartcampusbackend.controller;

import com.smartcampusbackend.model.ActivitySignup;
import com.smartcampusbackend.model.User;
import com.smartcampusbackend.service.ActivitySignupService;
import com.smartcampusbackend.service.TokenService;
import com.smartcampusbackend.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/activity/signup")
@CrossOrigin(origins = "*")
public class ActivitySignupController {
    @Autowired
    private ActivitySignupService activitySignupService;
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private TokenService tokenService;

//活动报名（老师、学生）
    @PostMapping
    public Map<String, Object> signup(@RequestBody ActivitySignup signup, @RequestHeader("Authorization") String token) {
        Map<String, Object> resp = new HashMap<>();
        try {
            // 从token获取用户信息
            if (token == null || !token.startsWith("Bearer ")) {
                resp.put("code", 401);
                resp.put("message", "无效的token");
                return resp;
            }
            
            String tokenValue = token.substring(7);
            String username = tokenService.getUsernameByToken(tokenValue);
            if (username == null) {
                resp.put("code", 401);
                resp.put("message", "token已过期");
                return resp;
            }
            
            // 根据用户名获取用户信息
            User user = userService.lambdaQuery().eq(User::getUsername, username).one();
            if (user == null) {
                resp.put("code", 404);
                resp.put("message", "用户不存在");
                return resp;
            }
            
            // 设置用户ID
            signup.setUserId(user.getId());
            signup.setSignupTime(new Date());
            signup.setStatus("PENDING"); // 设置默认状态为待审批
            int result = activitySignupService.signup(signup);
            resp.put("code", result > 0 ? 200 : 500);
            resp.put("message", result > 0 ? "报名成功" : "报名失败");
        } catch (RuntimeException e) {
            resp.put("code", 400);
            resp.put("message", e.getMessage());
        }
        return resp;
    }

    //获取审批列表（管理员，支持状态筛选）
    @GetMapping("/approval-list")
    public Map<String, Object> getApprovalList(@RequestParam Integer activityId,
                                               @RequestParam(required = false) String status,
                                               @RequestParam String publisher) {
        Map<String, Object> resp = new HashMap<>();
        try {
            // 验证权限：只有活动发布者可以查看审批列表
            if (!activitySignupService.canManageActivity(activityId, publisher)) {
                resp.put("code", 403);
                resp.put("message", "无权限查看该活动的审批列表");
                return resp;
            }
            
            List<ActivitySignup> list = activitySignupService.getApprovalList(activityId, status);
            resp.put("code", 200);
            resp.put("data", list);
        } catch (RuntimeException e) {
            resp.put("code", 400);
            resp.put("message", e.getMessage());
        }
        return resp;
    }

//审批报名（管理员）
    @PostMapping("/approve")
    public Map<String, Object> approve(@RequestParam Integer id, 
                                      @RequestParam String status,
                                      @RequestParam String publisher) {
        Map<String, Object> resp = new HashMap<>();
        try {
            // 先获取报名信息
            ActivitySignup signup = activitySignupService.getSignupById(id);
            if (signup == null) {
                resp.put("code", 404);
                resp.put("message", "报名记录不存在");
                return resp;
            }
            
            Integer activityId = signup.getActivityId();
            
            // 验证权限：只有活动发布者可以审批
            if (!activitySignupService.canManageActivity(activityId, publisher)) {
                resp.put("code", 403);
                resp.put("message", "无权限审批该活动的报名");
                return resp;
            }
            
            int result = activitySignupService.approveSignup(id, status);
            resp.put("code", result > 0 ? 200 : 500);
            resp.put("message", result > 0 ? "审批成功" : "审批失败");
        } catch (RuntimeException e) {
            resp.put("code", 400);
            resp.put("message", e.getMessage());
        }
        return resp;
    }
//获取活动人员名单（管理员）
    @GetMapping("/list")
    public Map<String, Object> list(@RequestParam Integer activityId,
                                   @RequestParam String publisher) {
        Map<String, Object> resp = new HashMap<>();
        try {
            // 验证权限：只有活动发布者可以查看人员名单
            if (!activitySignupService.canManageActivity(activityId, publisher)) {
                resp.put("code", 403);
                resp.put("message", "无权限查看该活动的人员名单");
                return resp;
            }
            
            List<ActivitySignup> list = activitySignupService.getSignupsByActivityId(activityId);
            resp.put("code", 200);
            resp.put("data", list);
        } catch (RuntimeException e) {
            resp.put("code", 400);
            resp.put("message", e.getMessage());
        }
        return resp;
    }

//检查活动是否可以报名
    @GetMapping("/check")
    public Map<String, Object> checkSignup(@RequestParam Integer activityId) {
        boolean canSignup = activitySignupService.canSignup(activityId);
        Map<String, Object> resp = new HashMap<>();
        resp.put("code", 200);
        resp.put("data", canSignup);
        resp.put("message", canSignup ? "可以报名" : "活动报名已截止或已满员");
        return resp;
    }
    
    //获取我的报名活动列表（学生、老师）
    @GetMapping("/my-signups")
    public Map<String, Object> getMySignups(@RequestParam String studentId) {
        List<ActivitySignup> list = activitySignupService.getMySignups(studentId);
        
        Map<String, Object> resp = new HashMap<>();
        resp.put("code", 200);
        resp.put("data", list);
        return resp;
    }
    
    //获取我的报名活动详细信息（学生、老师）
    @GetMapping("/my-signup-details")
    public Map<String, Object> getMySignupDetails(@RequestParam String studentId) {
        List<com.smartcampusbackend.model.ActivitySignupDetail> list = activitySignupService.getMySignupDetails(studentId);
        Map<String, Object> resp = new HashMap<>();
        resp.put("code", 200);
        resp.put("data", list);
        return resp;
    }
    
    //根据用户ID获取报名活动列表
    @GetMapping("/user-signups")
    public Map<String, Object> getUserSignups(@RequestHeader("Authorization") String token) {
        Map<String, Object> resp = new HashMap<>();
        try {
            // 从token获取用户信息
            if (token == null || !token.startsWith("Bearer ")) {
                resp.put("code", 401);
                resp.put("message", "无效的token");
                return resp;
            }
            
            String tokenValue = token.substring(7);
            String username = tokenService.getUsernameByToken(tokenValue);
            if (username == null) {
                resp.put("code", 401);
                resp.put("message", "token已过期");
                return resp;
            }
            
            // 根据用户名获取用户信息
            User user = userService.lambdaQuery().eq(User::getUsername, username).one();
            if (user == null) {
                resp.put("code", 404);
                resp.put("message", "用户不存在");
                return resp;
            }
            
            List<ActivitySignup> list = activitySignupService.getSignupsByUserId(user.getId());
            resp.put("code", 200);
            resp.put("data", list);
        } catch (Exception e) {
            resp.put("code", 500);
            resp.put("message", "查询失败：" + e.getMessage());
        }
        return resp;
    }
    
    //根据用户ID获取报名活动详细信息
    @GetMapping("/user-signup-details")
    public Map<String, Object> getUserSignupDetails(@RequestHeader("Authorization") String token) {
        Map<String, Object> resp = new HashMap<>();
        try {
            // 从token获取用户信息
            if (token == null || !token.startsWith("Bearer ")) {
                resp.put("code", 401);
                resp.put("message", "无效的token");
                return resp;
            }
            
            String tokenValue = token.substring(7);
            String username = tokenService.getUsernameByToken(tokenValue);
            if (username == null) {
                resp.put("code", 401);
                resp.put("message", "token已过期");
                return resp;
            }
            
            // 根据用户名获取用户信息
            User user = userService.lambdaQuery().eq(User::getUsername, username).one();
            if (user == null) {
                resp.put("code", 404);
                resp.put("message", "用户不存在");
                return resp;
            }
            
            List<com.smartcampusbackend.model.ActivitySignupDetail> list = activitySignupService.getSignupDetailsByUserId(user.getId());
            resp.put("code", 200);
            resp.put("data", list);
        } catch (Exception e) {
            resp.put("code", 500);
            resp.put("message", "查询失败：" + e.getMessage());
        }
        return resp;
    }

} 